package lion.bugrambo.execution;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;

import lion.bugrambo.model.Project;
import lion.bugrambo.model.Requirement;
import lion.dev.lang.MapJ;
import lion.dev.text.Formater;
import lion.dev.web.Validator;
import lion.dev.web.paging.PagedVo;
import lion.framework.core.db.DB;
import lion.framework.core.db.DataTable;
import lion.framework.core.db.SQLJoin;
import lion.framework.core.db.SessionFactory;
import lion.framework.core.db.paging.SQLPagingFactory;
import lion.framework.core.web.anno.Namespace;
import lion.framework.core.web.anno.Path;
import lion.framework.core.web.anno.Result;
import lion.framework.core.web.anno.View;
import lion.framework.core.web.request.Request;
import lion.framework.core.web.views.ResultType;
import lion.web.export.ExcelExporter;
import lion.web.platform.priv.user.LoginUser;

/**
 * 需求管理
 * 
 * @author lion
 * @email hl_0074@sina.com
 * @date 2015年4月3日
 */
@Namespace("#{admin}/br")
public class RequirementExecution {

	@Path("/requirement")
	@Result(@View("/WEB-INF/template/bugrambo/requirement/index.jsp"))
	public String index() {

		return "success";
	}

	@Path("/requirment/list")
	@Result(@View(type = ResultType.JSON))
	public String list(Request request) {

		int projectId = request.getInt("projectId");
		if (projectId < 0) { return "success"; }
		int page = request.getInt("page", 1);
		int size = request.getInt("size", 30);

		SQLJoin sqlJoin = new SQLJoin();
		sqlJoin.add("projectId=:projectId");
		int moduleId = request.getInt("modelId");
		if (moduleId > 0) {
			sqlJoin.add("moduleId=:modelId");
		}
		int status = request.getInt("status");
		if (status > 0) {
			sqlJoin.add("status=:status");
		}

		PagedVo<Requirement> vos = new PagedVo<>(Requirement.count("where " + sqlJoin.toString(), request));
		vos.getPaging().setPageNumber(page);
		vos.getPaging().setPageSize(size);

		String sql = "select r.*,(select u.realName from User u where u.id=r.creator) creatorName,(select name from ProjectModel where id=r.moduleId) moduleName from Requirement r ";

		String sort = request.getString("col");
		String order = request.getString("order");
		if (StringUtils.isBlank(sort)) {
			sort = "id";
		}
		sqlJoin.addSort(sort, order);
		sql += " where " + sqlJoin.toString();

		DB db = SessionFactory.getCurrentDB();
		DataTable dt = db.query(SQLPagingFactory.paging(db.getType(), sql, vos.getPaging().getStartRowNumber(), vos.getPaging().getPageSize()), request);

		request.addModel("vos", dt.getRows());
		request.addModel("pageing", vos.getPaging());

		return "success";
	}

	@Path("/requirment/edit")
	@Result(@View("/WEB-INF/template/bugrambo/requirement/edit.jsp"))
	public String edit(Request request) {

		int projectId = request.getInt("projectId");
		int id = request.getInt("id");
		if (id > -1) {
			Requirement requirement = Requirement.load(id);
			if (requirement != null) {
				request.addModel("requirement", requirement);
				projectId = requirement.getProjectId();
			}
		}

		request.addModel("project", Project.load(projectId));

		return "success";
	}

	@Path("/requirment/save")
	public void save(Request request) {

		Requirement requirement = Requirement.create(request);

		requirement.setCreateTime(new Date());
		requirement.setCreator(LoginUser.current().getUser().getId());
		requirement.save();
	}

	@Path("/requirment/delete")
	public void delete(Request request) {

		int[] ids = Validator.toIntArray(request.getString("ids"));
		if (ids.length == 0) { return; }
		Requirement.delete(ids);
	}

	@Path("/requirment/update")
	public void update(Request request) {

		Requirement requirement = Requirement.load(request.getInt("id"));

		requirement.setTitle(request.getString("title"));
		requirement.setContent(request.getString("content"));
		requirement.setModuleId(request.getInt("moduleId"));
		requirement.setStatus(request.getInt("status"));

		requirement.update();
	}

	@Path("/requirment/export")
	@Result(@View(type = "excel"))
	public String export(Request request) {

		SQLJoin sqlJoin = new SQLJoin();
		sqlJoin.add("projectId=:projectId");
		int moduleId = request.getInt("modelId");
		if (moduleId > 0) {
			sqlJoin.add("moduleId=:modelId");
		}
		int status = request.getInt("status");
		if (status > 0) {
			sqlJoin.add("status=:status");
		}
		String sql = "select r.*,(select u.realName from User u where u.id=r.creator) creatorName,(select name from ProjectModel where id=r.moduleId) moduleName from Requirement r ";
		sqlJoin.addSort("id", "desc");
		sql += " where " + sqlJoin.toString();

		DB db = SessionFactory.getCurrentDB();
		DataTable dt = db.query(sql, request);

		List<MapJ> rows = dt.getRows();

		for (MapJ row : rows) {

			int st = row.getInt("status");
			String text = "";
			if (st == 1) {
				text = "等待";
			} else if (st == 2) {
				text = "进行中";
			} else if (st == 3) {
				text = "已完成";
			} else if (st == 4) {
				text = "抛　弃";
			}
			row.put("status", text);

			row.put("createTime", Formater.formatDate("yyyy-MM-dd HH:mm:ss", row.getDate("createTime")));
		}

		String pname = "";

		Project project = Project.load(request.getInt("projectId"));
		if (project != null) {
			pname = project.getName();
		}

		Workbook workbook = ExcelExporter.create(pname + "-需求列表", dt.getRows(),
				new String[][] { { "status", "状态" }, { "title", "标题" }, { "moduleName", "模块名" }, { "creatorName", "创建者" }, { "createTime", "创建时间" } });

		request.addModel("workbook", workbook);
		request.addModel("name", "Requirements.xls");

		return "success";
	}
}
